package com.mhz.widgets.client.multicombo;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Widget;
import com.mhz.widgets.client.multicombo.MultiComboList.MultiComboSelectHandler;
import com.mhz.widgets.client.resources.WidgetsResource;
import com.mhz.widgets.shared.MultiComboItem;

public class MultiComboWidget extends Composite {

	private static ViewWidgetUiBinder uiBinder = GWT.create(ViewWidgetUiBinder.class);

	interface ViewWidgetUiBinder extends UiBinder<Widget, MultiComboWidget> {
	}

	@UiField
	HTMLPanel multiSelectPanel;

	@UiField
	InlineLabel comboTitle;

	@UiField
	Image comboImgArrow;

	@UiField
	MultiComboList comboListItems;

	public MultiComboWidget(String comboLabel, String width) {
		// Init uiBinder
		initWidget(uiBinder.createAndBindUi(this));
		// Set widget properties
		multiSelectPanel.setWidth(width);
		comboListItems.getScrollPanel().setSize(width, "140px");
		comboTitle.setText(comboLabel);
		// Set combo arrow image
		comboImgArrow.setResource(WidgetsResource.instance.comboArrow());
		comboListItems.setVisible(false);
	}

	@UiHandler("comboImgArrow")
	public void clickComboArrow(MouseDownEvent event) {
		comboListItems.setVisible(true);
		comboListItems.show();
	}

	public void setComboItems(List<MultiComboItem> items) {
		comboListItems.setListContent(items);
	}

	public void removeItem(String filterCode) {
		List<String> newSelectedItems = new ArrayList<String>();
		for (MultiComboItem item : comboListItems.getSelectedItems()) {
			if (!item.getValue().equalsIgnoreCase(filterCode)) {
				newSelectedItems.add(item.getCode());
			}
		}
		comboListItems.setSelectedItems(newSelectedItems);
	}

	public void addSelectHandler(MultiComboSelectHandler selectHandler) {
		comboListItems.addSelectHandler(selectHandler);
	}

}
